//1、导入koa-router
const Router = require('koa-router')
//2、实例化router对象
const router = new Router({prefix:'/user'})

const db = [
    {id:1,name:'小明',age:18},
    {id:2,name:'小红',age:28},
    {id:3,name:'小刚',age:38},
]

// GET /user?start=xx&end=xx
router.get('/',(ctx) => {
    // 通过 ctx.query 来解析键值对参数，是ctx.request.query的代理
    const {start=0, end=0} = ctx.query
    if(start >= end) ctx.throw(422)
    const res = db.filter(item => {
        return item.age >= start && item.age <= end
    })
    res.length == 0 ? ctx.throw(404) : ctx.body = res
})

// GET /user/:id
router.get('/:id',(ctx) => {
    const id = ctx.params.id
    const res = db.filter(item => {
        return item.id == id
    })
    if(res.length == 0) ctx.throw(404)  

    ctx.body = res
})

// POST /user
router.post('/',(ctx) => {
    console.log(ctx.request.body)
})

// GET /user/error/test
router.get('/error/test',(ctx)=>{
    if(false){
        ctx.body = {id:1,title:'文章',content:'文章'}
    }else{
        // // 错误处理，发布错误
        // return ctx.app.emit('error',{code:404,message:'资源没找到'},ctx)
        ctx.throw(422,"参数格式不对")
    }
})

module.exports = router
